package org.xxpay.pay.channel.huypay;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.MyBase64;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.PayConfig;
import org.xxpay.pay.ctrl.common.BaseController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 聚合固码通道
 * @author xxpay
 * @date 2019-02-13
 */
@Controller
public class HuypayController extends BaseController {

	private static final MyLog _log = MyLog.getLog(HuypayController.class);

	private static Map<String, String> qrTypeMap = new HashMap<>();
	static {
		qrTypeMap.put("wxpay", "微信");
		qrTypeMap.put("alipay", "支付宝");
		qrTypeMap.put("cloudmoney", "云闪付");
	}

	@Autowired
	public PayConfig payConfig;

	/**
	 * 转到前端收银台界面
	 * @param request
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/api/"+ HuypayConfig.CHANNEL_NAME +"/pay_{type}.htm")
	public String toCashier(HttpServletRequest request, ModelMap model, @PathVariable("type") String type) {
		JSONObject po = getJsonParam(request);
		String param = getString(po, "param");
		String paramStr = new String(MyBase64.decode(param));
		JSONObject paramObj = JSONObject.parseObject(paramStr);
		String payAmount = getString(paramObj,"payAmount"); //用户支付金额
		String payOrderId = getString(paramObj,"payOrderId"); //本系统支付订单号
		String channelId = getString(paramObj,"channelId"); //支付渠道， 用于判断支付类型
		String qrUrl = getString(paramObj,"qrUrl"); //二维码真实地址

		//验证参数是否合法
		if(StringUtils.isAnyEmpty(payAmount, payOrderId, channelId, qrUrl)){
			return null;
		}

		PayOrder payOrder = commonService.payOrderService.findByPayOrderId(payOrderId);
		if(payOrder == null){
			return "payment/huypay/pay_cashier";
		}

		//时间倒计时
		long timerSecond = HuypayConfig.PAY_ORDER_TIME_OUT;
		request.setAttribute("timerSecond", timerSecond);
		DBApplicationConfig dbConfig = commonService.sysConfigService.getDBApplicationConfig();

		model.put("payAmount", AmountUtil.convertCent2Dollar(payAmount));
		model.put("payOrderId", payOrderId);
		model.put("imgSrc", dbConfig.getConfig4PayUrl() + "/qrcode_img_get?url=" + URLEncoder.encode(qrUrl) + "&width=200&height=200");

		//ws地址： ws://localhost:8088/ws/payOrder/P11100001/20180010101
		String payDomain = dbConfig.getConfig4PayUrl().replace("http://", "").replace("https://", "").replace("/api",""); //去掉http协议
		String wsProtocol = dbConfig.getConfig4PayUrl().startsWith("http://") ? "ws://" : "wss://"; //ws协议
		model.put("wsAddress", wsProtocol + payDomain + "/ws/payOrder/" + payOrderId + "/" + new Date().getTime());

		model.put("payOrderState", payOrder.getStatus());
		//String qrTypeCode = channelId.substring(channelId.indexOf("_") + 1);

		String qrTypeCode = "wxpay";
		if(channelId.startsWith("huypay_qr")) {
			qrTypeCode = channelId.replace("huypay_", "");
		}

		String requestHeader = request.getHeader("user-agent");
		boolean isMobile = isMobileDevice(requestHeader);
		String payTip = "";
		boolean isJumpWap = false;
		String jumpUrl = "";
		String qrTypeName = qrTypeMap.get(qrTypeCode);
		if(isMobile) {
			if("alipay".equals(qrTypeCode)) {
				payTip = "请截屏保存二维码，打开["+qrTypeName+"]-[扫一扫]-[相册]-选取二维码";
				isJumpWap = true;
				String qrId = qrUrl.substring(qrUrl.lastIndexOf("/")+1);
				jumpUrl = String.format("https://mobilecodec.alipay.com/client_download.htm?qrcode=%s&t=%s", qrId, System.currentTimeMillis());
			}else if("wxpay".equals(qrTypeCode)) {
				payTip = "请截屏保存二维码，打开["+qrTypeName+"]-[扫一扫]-从相册选取二维码";
			}else if("cloudmoney".equals(qrTypeCode)) {
				payTip = "请截屏保存二维码，打开["+qrTypeName+"]-[扫一扫]-[打开相册]-选取二维码";
			}else {

				if(channelId.indexOf("alipay") > 0) {
					qrTypeName = "支付宝";
					payTip = "请截屏保存二维码，打开[支付宝]-[扫一扫]-[相册]-选取二维码";
					isJumpWap = true;
					jumpUrl = qrUrl;
				}else if(channelId.indexOf("wxpay") > 0) {
					qrTypeName = "微信";
					payTip = "请截屏保存二维码，打开[微信]-[扫一扫]-[相册]-选取二维码";
					isJumpWap = false;
				}

			}
		}else {
			if("alipay".equals(qrTypeCode) || "wxpay".equals(qrTypeCode) || "cloudmoney".equals(qrTypeCode)) {
				payTip = "请用["+qrTypeName+"]-[扫一扫]付款";
			}else {
				qrTypeName = "支付宝或微信";
				payTip = "请用 [支付宝或微信]-[扫一扫] 付款";
			}
		}
		model.put("payTip", payTip);
		model.put("isMobile", isMobile);
		model.put("isJumpWap", isJumpWap);
		model.put("jumpUrl", jumpUrl);
		model.put("qrTypeName", qrTypeName);
		model.put("qrTypeCode", qrTypeCode);
		return "payment/huypay/pay_cashier";
	}

	/**
	 * 查询订单
	 * @param request
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/api/"+ HuypayConfig.CHANNEL_NAME+"/query")
	@ResponseBody
	public String toQuery(HttpServletRequest request) {
		JSONObject po = getJsonParam(request);
		String payOrderId = getString(po, "payOrderId");
		_log.info("[查询订单]参数payOrderId={}", payOrderId);

		PayOrder payOrder = commonService.payOrderService.findByPayOrderId(payOrderId);
		JSONObject retObj = new JSONObject();
		String status = "-1";
		String url = "";
		if(payOrder != null) {
			status = payOrder.getStatus() + "";
			url = payOrder.getReturnUrl();
		}
		retObj.put("status", status);
		retObj.put("url", url);
		_log.info("[查询订单]结果payOrderId={},retObj={}", payOrderId, retObj);
		return retObj.toJSONString();
	}

	public static boolean  isMobileDevice(String requestHeader){
		/**
		 * android : 所有android设备
		 * ios : iphone ipad
		 * windows phone:Nokia等windows系统的手机
		 */
		String[] deviceArray = new String[]{"android","iphone","ipad","windows phone"};
		if(requestHeader == null)
			return false;
		requestHeader = requestHeader.toLowerCase();
		for(int i=0;i<deviceArray.length;i++){
			if(requestHeader.indexOf(deviceArray[i])>0){
				return true;
			}
		}
		return false;
	}

}
